﻿using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using XiaoYuJi.Core.Extens;
using XiaoYuJi.Core.Jwt;
using XiaoYuJi.Entity;
using XiaoYuJi.Entity.Dtos.SystemDtos;
using XiaoYuJi.Entity.SysEntitys;

namespace XiaoYuJi.Service.SysServices;
public class AuthService : IAuthService
{
    private readonly IUserService _userService;
    private readonly IOptions<TokenManagement> _tokenManagement;

    public AuthService(IUserService userService,IOptions<TokenManagement> tokenManagement)
    {
        this._userService = userService;
        this._tokenManagement = tokenManagement;
    }


    /// <summary>
    /// 后台管理系统登录
    /// </summary>
    /// <param name="userName">用户名</param>
    /// <param name="password">密码</param>
    /// <returns></returns>
    public async Task<ApiResult<AuthDto>> AdminLogin(string userName, string password)
    {
        ApiResult<AuthDto> apiResult = new();

        //验证用户名、密码是否正确
        SysUser user = await _userService.VerifyUser(userName, password);
        if (user == null)
        {
            apiResult.Code = -1;    //-1代表出现错误
            apiResult.Message = "用户信息不存在！";
            return apiResult;
        }

        //存在用户信息，生成token
        List<Claim> claimList = new()
        {
            new Claim(ClaimTypes.Sid,user.Id.ToString()),
            new Claim(ClaimTypes.Surname,user.UserName),
            new Claim(ClaimTypes.Name,user.Name??""),
            new Claim(ClaimTypes.Email,user.Email??""),
            new Claim(ClaimTypes.Role,user.SysRole.RoleName??"")
        }; 

        //生成token
        string token = JwtHelper.CreateToken(claimList.ToArray(), _tokenManagement.Value);
        if (token.IsNullOrEmpty())
        {
            apiResult.Code = -1;    //-1代表出现错误
            apiResult.Message = "用户信息验证异常！";
            return apiResult;
        }

        apiResult.Code = 200;
        apiResult.Data = new AuthDto
        {
            Token = token,
            VerifyResult = true,
            Data = new
            {
                UserId = user.Id,
                UserName = user.UserName,
                Name = user.Name,
                Email = user.Email,
                RoleName = user.SysRole.RoleName,
            }
        };
        apiResult.Message = "系统用户登录成功！";


        return apiResult;
    }



}
